﻿using Learun.Util;
using Learun.Util.SqlSugar;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DbType = System.Data.DbType;

namespace Learun.Application.Base.AuthorizeModule
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创建人：研发部
    /// 日 期：2017.04.17
    /// 描 述：用户关联对象
    /// </summary>
    public class UserRelationService
    {
        #region 仓储
        Repository<UserRelationEntity> _userRelationRepository => new Repository<UserRelationEntity>();
        #endregion
        #region 构造函数和属性
        private string fieldSql;
        public UserRelationService()
        {
            fieldSql = @"
                t.F_UserRelationId,
                t.F_UserId,
                t.F_Category,
                t.F_ObjectId,
                t.F_CreateDate,
                t.F_CreateUserId,
                t.F_CreateUserName,
                t.ProjectId
            ";
        }
        #endregion

        #region 获取数据
        /// <summary>
        /// 获取对象主键列表信息
        /// </summary>
        /// <param name="userId">用户主键</param>
        /// <param name="category">分类:1-角色2-岗位</param>
        /// <param name="ProjectId">项目id</param>
        /// <returns></returns>
        public IEnumerable<UserRelationEntity> GetObjectIdList(string userId, int category, string ProjectId = "")
        {
            try
            {
                var strSql = new StringBuilder();
                strSql.Append(" SELECT ");
                strSql.Append(fieldSql);
                strSql.Append(" FROM LR_Base_UserRelation t WHERE t.F_UserId = @userId AND t.F_Category = @category ");
                if (string.IsNullOrEmpty(ProjectId))
                {
                    strSql.Append("AND IFNULL(t.ProjectId,'') = '' ");
                }
                else
                {
                    strSql.Append("AND t.ProjectId = @ProjectId ");
                }
                //return this.BaseRepository().FindList<UserRelationEntity>(strSql.ToString(), new { userId = userId, category = category, ProjectId = ProjectId });
                return SqlSugarHelper.Db.SqlQueryable<UserRelationEntity>(strSql.ToString()).AddParameters(new { userId = userId, category = category, ProjectId = ProjectId }).ToList();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 获取用户主键列表信息
        /// </summary>
        /// <param name="objectId">关联角色或岗位组件</param>
        /// <param name="ProjectId">项目id</param>
        /// <returns></returns>
        public IEnumerable<UserRelationEntity> GetUserIdList(string objectId, string ProjectId = "")
        {
            try
            {
                var strSql = new StringBuilder();
                strSql.Append(" SELECT ");
                strSql.Append("t.* ");
                strSql.Append(" FROM LR_Base_UserRelation t WHERE 1=1 ");
                //var dp = new DynamicParameters(new { });
                var dp = new List<SugarParameter>();
                if (!string.IsNullOrEmpty(ProjectId))
                {
                    dp.Add(new SugarParameter("ProjectId", ProjectId, DbType.String));
                    strSql.Append("AND t.ProjectId = @ProjectId ");
                }
                else
                {
                    strSql.Append("AND IFNULL(t.ProjectId,'') = '' ");
                }
                if (!string.IsNullOrEmpty(objectId))
                {
                    dp.Add(new SugarParameter("objectId", objectId, DbType.String));
                    strSql.Append("AND t.F_ObjectId = @objectId ");
                }
                //return this.BaseRepository().FindList<UserRelationEntity>(strSql.ToString(), dp);
                return SqlSugarHelper.Db.SqlQueryable<UserRelationEntity>(strSql.ToString()).AddParameters(dp).ToList();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 获取用户主键列表信息
        /// </summary>
        /// <param name="objectIdList">关联主键集合</param>
        /// <param name="ProjectId">项目id</param>
        /// <returns></returns>
        public IEnumerable<UserRelationEntity> GetUserIdList(List<string> objectIdList, string ProjectId = "")
        {
            try
            {
                if (!string.IsNullOrEmpty(ProjectId))
                {
                    return _userRelationRepository.GetList(t => objectIdList.Contains(t.F_ObjectId) && t.ProjectId == ProjectId);
                }
                else
                {
                    return _userRelationRepository.GetList(t => objectIdList.Contains(t.F_ObjectId) && string.IsNullOrEmpty(t.ProjectId));
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 根据用户获取岗位
        /// </summary>
        /// <param name="userid">用户主键</param>
        /// <param name="ProjectId">项目id</param>
        /// <returns></returns>
        public IEnumerable<UserRelationEntity> GetObjectIdByUserId(string userid, string ProjectId = "")
        {
            try
            {
                if (!string.IsNullOrEmpty(ProjectId))
                {
                    return _userRelationRepository.GetList(t => t.F_UserId == userid && t.ProjectId == ProjectId);
                }
                else
                {
                    return _userRelationRepository.GetList(t => t.F_UserId == userid && string.IsNullOrEmpty(ProjectId));
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        #endregion

        #region 提交数据
        /// <summary>
        /// 保存用户对应对象数据
        /// </summary>
        /// <param name="RoleId">对象主键</param>
        /// <param name="ProjectId">项目id</param>
        /// <param name="userRelationEntityList">列表</param>
        public void SaveEntityList(string RoleId, string ProjectId, IEnumerable<UserRelationEntity> userRelationEntityList)
        {
            //var db = this.BaseRepository().BeginTrans();
            SqlSugarHelper.Db.BeginTran();
            try
            {
                if (!string.IsNullOrEmpty(ProjectId))
                {


                    //删除整个Role的分配，然后重新建立
                    _userRelationRepository.Delete(t => t.F_ObjectId.Equals(RoleId) && t.ProjectId == ProjectId);
                }
                else
                {
                    _userRelationRepository.Delete(t => t.F_ObjectId.Equals(RoleId) && string.IsNullOrEmpty(t.ProjectId));
                }

                //foreach (UserRelationEntity userRelationEntity in userRelationEntityList)
                //{        
                //删除原来的，确保一个用户只在一个Role里
                _userRelationRepository.Delete(t => userRelationEntityList.Select(x => x.F_UserId).Contains(t.F_UserId) && t.ProjectId == ProjectId);
                _userRelationRepository.InsertRange(userRelationEntityList.ToArray());
                //    .Insert(userRelationEntity);
                //}
                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 保存用户对应对象数据 角色  
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <param name="userRelationEntity">实体</param>
        public void SaveEntity(string keyValue, UserRelationEntity userRelationEntity)
        {

            try
            {
                if (string.IsNullOrEmpty(keyValue))
                {
                    userRelationEntity.Create();
                    //this.BaseRepository().Insert(userRelationEntity);
                    _userRelationRepository.Insert(userRelationEntity);
                }
                else
                {
                    userRelationEntity.Modify(keyValue);
                    //this.BaseRepository().Update(userRelationEntity);
                    _userRelationRepository.Update(userRelationEntity);
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 删除角色关联信息
        /// <param name="category">分类:1-角色2-岗位</param>
        /// <param name="userId">对用户主键</param>
        /// <param name="ProjectId">项目id</param>
        /// <summary>
        /// <returns></returns>
        public void DeleteEntity(int category, string userId, string ProjectId)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                if (string.IsNullOrEmpty(ProjectId))
                {
                    _userRelationRepository.Delete(t => t.F_UserId == userId && t.F_Category == category && string.IsNullOrEmpty(t.ProjectId));
                }
                else
                {
                    _userRelationRepository.Delete(t => t.F_UserId == userId && t.F_Category == category && t.ProjectId == ProjectId);
                }
                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 删除关联人员        
        /// <param name="keyValue">用户id</param>
        /// <param name="objectId">关联主键id</param>
        /// <param name="ProjectId">项目id</param>
        /// <summary>
        /// <returns></returns>
        public void DeleteUser(string keyValue, string objectId, string ProjectId)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                if (string.IsNullOrEmpty(ProjectId))
                {
                    _userRelationRepository.Delete(t => t.F_ObjectId == objectId && t.F_UserId == keyValue && string.IsNullOrEmpty(t.ProjectId));
                }
                else
                {
                    _userRelationRepository.Delete(t => t.F_ObjectId == objectId && t.F_UserId == keyValue && t.ProjectId == ProjectId);
                }
                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        #endregion
    }
}
